/**
 * Copyright (c) 2011-2013, kidzhou 周磊 (zhouleib1412@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.eystar.ext.kit;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

public class RecordKit {

	protected final static Log logger = Log.getLog(RecordKit.class);

	/**
	 * 将Record转成Model
	 * 
	 * @param clazz
	 * @param record
	 * @return
	 */
	public static Model<?> toModel(Class<? extends Model<?>> clazz, Record record) {
		Model<?> model = null;
		try {
			model = clazz.newInstance();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return model;
		}
		for (String columnName : record.getColumnNames()) {
			model.put(columnName, record.get(columnName));
		}
		return model;
	}

	/**
	 * 将JSONObject转成Record
	 * 
	 * @param clazz
	 * @param object
	 * @return
	 */
	public static Record toRecord(Class<? extends Record> clazz, JSONObject object) {
		Record record = null;
		try {
			record = clazz.newInstance();
		} catch (Exception e) {
			return record;
		}
		for (String columnName : object.keySet()) {
			record.set(columnName, object.get(columnName));
		}
		return record;
	}

	/**
	 * 将请求转换成Record对象。额外的参数必须是成对出现，并且参数的key是字符串类型
	 * 
	 * @param request
	 * @return
	 */
	public static Record toRecord(HttpServletRequest request, Object... attrsAndValues) {
		int length = attrsAndValues.length;
		if (length % 2 != 0) {
			throw new IllegalArgumentException("额外参数必须是成对出现");
		}
		Record record = new Record();
		for (int i = 0; i < length; i = i + 2) {
			Object attr = attrsAndValues[i];
			if (!(attr instanceof String)) {
				throw new IllegalArgumentException("参数的key必须是String类型");
			}
			record.set((String) attr, attrsAndValues[i + 1]);
		}
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements()) {
			String ele = params.nextElement();
			if (!StrKit.isBlank(request.getParameter(ele))) {
				record.set(ele, request.getParameter(ele).trim());
			}
		}
		return record;
	}
}
